<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="本篇将重点关注 Sentienl 实时数据收集，即 Sentienl 具体是如何收集调用信息，以此来判断是否需要触发限流或熔断。 Sentienl 实时数据收集的入口类为 StatisticSlot。 我们先简单来看一下 StatisticSlot 该类的注释，来看一下该类的整体定位。 StatisticSlot，专用于实时统计的 slot。在进入一个资源时，在执行 Sentienl 的处理链条中">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析 Sentinel 实时数据采集实现原理">
<meta property="og:url" content="https://www.codingw.net/posts/5f8f7185.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="本篇将重点关注 Sentienl 实时数据收集，即 Sentienl 具体是如何收集调用信息，以此来判断是否需要触发限流或熔断。 Sentienl 实时数据收集的入口类为 StatisticSlot。 我们先简单来看一下 StatisticSlot 该类的注释，来看一下该类的整体定位。 StatisticSlot，专用于实时统计的 slot。在进入一个资源时，在执行 Sentienl 的处理链条中">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200119210911647.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200119211057921.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200119211434219.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2020-09-22T14:47:35.000Z">
<meta property="article:modified_time" content="2021-04-26T12:08:39.880Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20200119210911647.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/5f8f7185.html"/>





  <title>源码分析 Sentinel 实时数据采集实现原理 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/5f8f7185.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析 Sentinel 实时数据采集实现原理</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-09-22T22:47:35+08:00">
                2020-09-22
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/sentinel/" itemprop="url" rel="index">
                    <span itemprop="name">sentinel</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/5f8f7185.html" class="leancloud_visitors" data-flag-title="源码分析 Sentinel 实时数据采集实现原理">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>本篇将重点关注 Sentienl 实时数据收集，即 Sentienl 具体是如何收集调用信息，以此来判断是否需要触发限流或熔断。</p>
<p>Sentienl 实时数据收集的入口类为 StatisticSlot。</p>
<p>我们先简单来看一下 StatisticSlot 该类的注释，来看一下该类的整体定位。</p>
<p>StatisticSlot，专用于实时统计的 slot。在进入一个资源时，在执行 Sentienl 的处理链条中会进入到该 slot 中，需要完成如下计算任务：</p>
<ul>
<li>集群维度计算资源的总统计信息，用于集群限流，后续文章将详细探讨。</li>
<li>来自不同调用方/来源的群集节点的统计信息。</li>
<li>特定调用上下文环境的统计信息。</li>
<li>统计所有入口的统计信息。</li>
</ul>
<p>接下来用源码分析的手段来详细分析 StatisticSlot 的实现原理。</p>
<h2 id="1、源码分析-StatisticSlot"><a href="#1、源码分析-StatisticSlot" class="headerlink" title="1、源码分析 StatisticSlot"></a>1、源码分析 StatisticSlot</h2><h4 id="1-1-StatisticSlot-entry-详解"><a href="#1-1-StatisticSlot-entry-详解" class="headerlink" title="1.1 StatisticSlot entry 详解"></a>1.1 StatisticSlot entry 详解</h4><p>StatisticSlot#entry </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">entry</span><span class="params">(Context context, ResourceWrapper resourceWrapper, DefaultNode node, <span class="keyword">int</span> count,<span class="keyword">boolean</span> prioritized, Object... args)</span> <span class="keyword">throws</span> Throwable </span>&#123; </span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		<span class="comment">// Do some checking.</span></span><br><span class="line">                fireEntry(context, resourceWrapper, node, count, prioritized, args);  <span class="comment">// @1</span></span><br><span class="line">        	<span class="comment">// Request passed, add thread count and pass count.</span></span><br><span class="line">        	node.increaseThreadNum();                                                             <span class="comment">// @2</span></span><br><span class="line">       		node.addPassRequest(count);</span><br><span class="line">		<span class="keyword">if</span> (context.getCurEntry().getOriginNode() != <span class="keyword">null</span>) &#123;                           <span class="comment">// @3</span></span><br><span class="line">			<span class="comment">// Add count for origin node.</span></span><br><span class="line">            		context.getCurEntry().getOriginNode().increaseThreadNum();</span><br><span class="line">            		context.getCurEntry().getOriginNode().addPassRequest(count);</span><br><span class="line">       		 &#125;</span><br><span class="line">		<span class="keyword">if</span> (resourceWrapper.getEntryType() == EntryType.IN) &#123;                <span class="comment">// @4</span></span><br><span class="line">			<span class="comment">// Add count for global inbound entry node for global statistics.</span></span><br><span class="line">            		Constants.ENTRY_NODE.increaseThreadNum();</span><br><span class="line">           	 	Constants.ENTRY_NODE.addPassRequest(count);</span><br><span class="line">        	&#125;</span><br><span class="line">		<span class="comment">// Handle pass event with registered entry callback handlers.</span></span><br><span class="line">        	<span class="keyword">for</span> (ProcessorSlotEntryCallback&lt;DefaultNode&gt; handler : StatisticSlotCallbackRegistry.getEntryCallbacks()) &#123;   <span class="comment">// @5</span></span><br><span class="line">            		handler.onPass(context, resourceWrapper, node, count, args);</span><br><span class="line">        	&#125;</span><br><span class="line">    	&#125; <span class="keyword">catch</span> (PriorityWaitException ex) &#123;                                                                                                                                <span class="comment">// @6</span></span><br><span class="line">		node.increaseThreadNum();</span><br><span class="line">		<span class="keyword">if</span> (context.getCurEntry().getOriginNode() != <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="comment">// Add count for origin node.</span></span><br><span class="line">            		context.getCurEntry().getOriginNode().increaseThreadNum();</span><br><span class="line">       	 	&#125;</span><br><span class="line">		<span class="keyword">if</span> (resourceWrapper.getEntryType() == EntryType.IN) &#123;</span><br><span class="line">			<span class="comment">// Add count for global inbound entry node for global statistics.</span></span><br><span class="line">            		Constants.ENTRY_NODE.increaseThreadNum();</span><br><span class="line">        	&#125;</span><br><span class="line">        	<span class="comment">// Handle pass event with registered entry callback handlers.</span></span><br><span class="line">        	<span class="keyword">for</span> (ProcessorSlotEntryCallback&lt;DefaultNode&gt; handler : StatisticSlotCallbackRegistry.getEntryCallbacks()) &#123;</span><br><span class="line">            		handler.onPass(context, resourceWrapper, node, count, args);</span><br><span class="line">        	&#125;</span><br><span class="line">    	&#125; <span class="keyword">catch</span> (BlockException e) &#123;     <span class="comment">// @7                                                                                                              </span></span><br><span class="line">        	<span class="comment">// Blocked, set block exception to current entry.</span></span><br><span class="line">        	context.getCurEntry().setError(e);</span><br><span class="line">		<span class="comment">// Add block count.</span></span><br><span class="line">        	node.increaseBlockQps(count);</span><br><span class="line">        	<span class="keyword">if</span> (context.getCurEntry().getOriginNode() != <span class="keyword">null</span>) &#123;</span><br><span class="line">            		context.getCurEntry().getOriginNode().increaseBlockQps(count);</span><br><span class="line">        	&#125;</span><br><span class="line">		<span class="keyword">if</span> (resourceWrapper.getEntryType() == EntryType.IN) &#123;</span><br><span class="line">            		<span class="comment">// Add count for global inbound entry node for global statistics.</span></span><br><span class="line">            		Constants.ENTRY_NODE.increaseBlockQps(count);</span><br><span class="line">        	&#125;</span><br><span class="line">        	<span class="comment">// Handle block event with registered entry callback handlers.</span></span><br><span class="line">        	<span class="keyword">for</span> (ProcessorSlotEntryCallback&lt;DefaultNode&gt; handler : StatisticSlotCallbackRegistry.getEntryCallbacks()) &#123;</span><br><span class="line">            		handler.onBlocked(e, context, resourceWrapper, node, count, args);</span><br><span class="line">        	&#125;</span><br><span class="line">		<span class="keyword">throw</span> e;</span><br><span class="line">    	&#125; <span class="keyword">catch</span> (Throwable e) &#123;   <span class="comment">// @8</span></span><br><span class="line">        	<span class="comment">// Unexpected error, set error to current entry.</span></span><br><span class="line">        	context.getCurEntry().setError(e);</span><br><span class="line">		<span class="comment">// This should not happen.</span></span><br><span class="line">        	node.increaseExceptionQps(count);</span><br><span class="line">        	<span class="keyword">if</span> (context.getCurEntry().getOriginNode() != <span class="keyword">null</span>) &#123;</span><br><span class="line">            		context.getCurEntry().getOriginNode().increaseExceptionQps(count);</span><br><span class="line">        	&#125;</span><br><span class="line">		<span class="keyword">if</span> (resourceWrapper.getEntryType() == EntryType.IN) &#123;</span><br><span class="line">            		Constants.ENTRY_NODE.increaseExceptionQps(count);</span><br><span class="line">        	&#125;</span><br><span class="line">        	<span class="keyword">throw</span> e;</span><br><span class="line">    	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先调用 fireEntry，先调用 Sentinel Slot Chain 中其他的处理器，执行完其他处理器的逻辑，例如 FlowSlot、DegradeSlot，因为 StatisticSlot 的职责是收集统计信息。</p>
<p>代码@2：如果后续处理器成功执行，则将正在执行线程数统计指标加一，并将通过的请求数量指标增加对应的值。下文会对 Sentinel Node 体系进行详细的介绍，在 Sentinel 中使用 Node 来表示调用链中的某一个节点，每个节点关联一个资源，资源的实时统计信息就存储在 Node 中，故该部分也是调用 DefaultNode 的相关方法来改变线程数等，将在下文会向详细介绍。</p>
<p>代码@3：如果上下文环境中保存了调用的源头（调用方）的节点信息不为空，则更新该节点的统计数据：线程数与通过数量。</p>
<p>代码@4：如果资源的进入类型为 EntryType.IN，表示入站流量，更新入站全局统计数据(集群范围 ClusterNode)。</p>
<p>代码@5：执行注册的进入Handler，可以通过 StatisticSlotCallbackRegistry 的 addEntryCallback 注册相关监听器。</p>
<p>代码@6：如果捕获到 PriorityWaitException ，则认为是等待过一定时间，但最终还是算通过，只需增加线程的个数，但无需增加节点通过的数量，具体原因我们在详细分析限流部分时会重点讨论，也会再次阐述 PriorityWaitException 的含义。</p>
<p>代码@7：如果捕获到 BlockException，则主要增加阻塞的数量。</p>
<p>代码@8：如果是系统异常，则增加异常数量。</p>
<p>我想上面的代码应该不难理解，但涉及到统计指标数据的变化，都是调用 DefaultNode node 相关的方法，从这里也可以看出，Node 将是实时统计数据的直接持有者，那毋容置疑接下来将重点来学习 Node，为了知识体系的完备性，我们先来看一下 StatisticSlot 的 exit 方法。</p>
<span id="more"></span>

<h4 id="1-2-StatisticSlot-exit-详解"><a href="#1-2-StatisticSlot-exit-详解" class="headerlink" title="1.2 StatisticSlot exit 详解"></a>1.2 StatisticSlot exit 详解</h4><p>StatisticSlot#exit </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">exit</span><span class="params">(Context context, ResourceWrapper resourceWrapper, <span class="keyword">int</span> count, Object... args)</span> </span>&#123;</span><br><span class="line">	DefaultNode node = (DefaultNode)context.getCurNode();</span><br><span class="line">	<span class="keyword">if</span> (context.getCurEntry().getError() == <span class="keyword">null</span>) &#123;         <span class="comment">// @1</span></span><br><span class="line">		<span class="comment">// Calculate response time (max RT is TIME_DROP_VALVE).</span></span><br><span class="line">		<span class="keyword">long</span> rt = TimeUtil.currentTimeMillis() - context.getCurEntry().getCreateTime();</span><br><span class="line">		<span class="keyword">if</span> (rt &gt; Constants.TIME_DROP_VALVE) &#123;</span><br><span class="line">			rt = Constants.TIME_DROP_VALVE;</span><br><span class="line">        	&#125;</span><br><span class="line">		<span class="comment">// Record response time and success count.</span></span><br><span class="line">		node.addRtAndSuccess(rt, count);</span><br><span class="line">		<span class="keyword">if</span> (context.getCurEntry().getOriginNode() != <span class="keyword">null</span>) &#123;</span><br><span class="line">			context.getCurEntry().getOriginNode().addRtAndSuccess(rt, count);</span><br><span class="line">       	        &#125;</span><br><span class="line">        node.decreaseThreadNum();</span><br><span class="line">	       <span class="keyword">if</span> (context.getCurEntry().getOriginNode() != <span class="keyword">null</span>) &#123;</span><br><span class="line">		    context.getCurEntry().getOriginNode().decreaseThreadNum();</span><br><span class="line">                &#125;</span><br><span class="line">	       <span class="keyword">if</span> (resourceWrapper.getEntryType() == EntryType.IN) &#123;</span><br><span class="line">                   Constants.ENTRY_NODE.addRtAndSuccess(rt, count);</span><br><span class="line">                   Constants.ENTRY_NODE.decreaseThreadNum();</span><br><span class="line">               &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// Error may happen.</span></span><br><span class="line">        &#125;</span><br><span class="line">	<span class="comment">// Handle exit event with registered exit callback handlers.</span></span><br><span class="line">        Collection&lt;ProcessorSlotExitCallback&gt; exitCallbacks = StatisticSlotCallbackRegistry.getExitCallbacks();</span><br><span class="line">        <span class="keyword">for</span> (ProcessorSlotExitCallback handler : exitCallbacks) &#123;      <span class="comment">// @2</span></span><br><span class="line">		handler.onExit(context, resourceWrapper, count, args);</span><br><span class="line">         &#125;</span><br><span class="line">	fireExit(context, resourceWrapper, count);     <span class="comment">// @3</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：成功执行，则重点关注响应时间，其实现亮点如下：<br>计算本次响应时间，将本次响应时间收集到 Node 中。<br>将当前活跃线程数减一。</p>
<p>代码@2：执行退出时的 callback。可以通过 StatisticSlotCallbackRegistry 的 addExitCallback 方法添加退出回调函数。</p>
<p>代码@3：传播 exit 事件。</p>
<p>接下来我们将重点介绍 DefaultNode，即 Sentinel 的 Node 体系，持有资源的实时调用信息。</p>
<h2 id="2、Sentienl-Node-体系"><a href="#2、Sentienl-Node-体系" class="headerlink" title="2、Sentienl Node 体系"></a>2、Sentienl Node 体系</h2><p>2.1 Node 类体系图<br><img src="https://img-blog.csdnimg.cn/20200119210911647.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>我们先简单介绍一下上述核心类的作用与核心接口或核心属性的含义。</p>
<ul>
<li>OccupySupport<br>支持抢占未来的时间窗口，有点类似借用“未来”的令牌。其核心方法如下：<ul>
<li>long tryOccupyNext(long currentTime, int acquireCount, double threshold)<br>尝试抢占未来的令牌，返回值为调用该方法的线程应该 sleep 的时间。<br>1、long currentTime<br>​        当前时间。<br>2、int acquireCount<br>本次需要申请的令牌个数。<br>​          3、double threshold<br>​              设置的阔值。</li>
</ul>
</li>
<li>long waiting()<br>获取当前已申请的未来的令牌的个数。</li>
<li>void addWaitingRequest(long futureTime, int acquireCount)<br>申请未来时间窗口中的令牌。</li>
<li>void addOccupiedPass(int acquireCount)<br>增加申请未来令牌通过的个数。</li>
<li>double occupiedPassQps()<br>当前抢占未来令牌的QPS。</li>
<li>Node<br>持有实时统计信息的节点。定义了收集统计信息与获取统计信息的接口，上面方法根据方法名称即可得知其含义，故这里就不一一罗列了。</li>
<li>StatisticNode<br>实现统计信息的默认实现类。</li>
<li>DefaultNode<br>用于在特定上下文环境中保存某一个资源的实时统计信息。</li>
<li>ClusterNode<br>实现基于集群限流模式的节点，将在集群限流模式部分详细介绍。</li>
<li>EntranceNode<br>用来表示调用链入口的节点信息。</li>
</ul>
<p>本文将详细介绍 DefaultNode 与  StatisticNode，重点阐述调用树与实时统计信息。DefaultNode 是 StatisticNode 的子类，我们先从 StatisticNode 开始 Node 体系的探究。</p>
<h2 id="2、StatisticNode-详解"><a href="#2、StatisticNode-详解" class="headerlink" title="2、StatisticNode 详解"></a>2、StatisticNode 详解</h2><h4 id="2-1-核心类图"><a href="#2-1-核心类图" class="headerlink" title="2.1 核心类图"></a>2.1 核心类图</h4><p><img src="https://img-blog.csdnimg.cn/20200119211057921.png" alt="在这里插入图片描述"><br>我们对其核心属性进行一一解读：</p>
<ul>
<li>Metric rollingCounterInSecond = new ArrayMetric(SampleCountProperty.SAMPLE_COUNT, IntervalProperty.INTERVAL)<br>每秒的实时统计信息，使用 ArrayMetric 实现，即基于滑动窗口实现，正是上篇文章详细介绍的，默认1s 采样 2次。即一个统计周期中包含两个滑动窗口。</li>
<li>Metric rollingCounterInMinute = new ArrayMetric(60, 60 * 1000, false)<br>每分钟实时统计信息，同样使用 ArrayMetric  实现，即基于滑动窗口实现。每1分钟，抽样60次，即包含60个滑动窗口，每一个窗口的时间间隔为 1s 。</li>
<li>LongAdder curThreadNum = new LongAdder()<br>当前线程计数器。</li>
<li>long lastFetchTime = -1<br>上一次获取资源的有效统计数据的时间，即调用 Node 的 metrics() 方法的时间。</li>
</ul>
<p>关于 ArrayMetric 滑动窗口设计与实现原理，请参考笔者的另一篇博文：<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/tn8rSHyv_hiJi6QDhfxuIA">Alibaba Seninel 滑动窗口实现原理(文末附原理图)</a></p>
<p>接下来我们挑选几个具有代表性的方法进行探究。</p>
<h4 id="2-2-addPassRequest"><a href="#2-2-addPassRequest" class="headerlink" title="2.2 addPassRequest"></a>2.2 addPassRequest</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addPassRequest</span><span class="params">(<span class="keyword">int</span> count)</span> </span>&#123;</span><br><span class="line">	rollingCounterInSecond.addPass(count);</span><br><span class="line">	rollingCounterInMinute.addPass(count);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>增加通过请求数量。即将实时调用信息向滑动窗口中进行统计。addPassRequest 即报告成功的通过数量。就是分别调用 秒级、分钟即对应的滑动窗口中添加数量，然后限流规则、熔断规则将基于滑动窗口中的值进行计算。</p>
<h4 id="2-3-totalRequest"><a href="#2-3-totalRequest" class="headerlink" title="2.3 totalRequest"></a>2.3 totalRequest</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">totalRequest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> rollingCounterInMinute.pass() + rollingCounterInMinute.block();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>获取当前时间戳的总请求数，获取分钟级时间窗口中的统计信息。</p>
<h4 id="2-4-successQps"><a href="#2-4-successQps" class="headerlink" title="2.4 successQps"></a>2.4 successQps</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">double</span> <span class="title">successQps</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> rollingCounterInSecond.success() / rollingCounterInSecond.getWindowIntervalInSec();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>成功TPS，用秒级统计滑动窗口中统计的个数 除以 窗口的间隔得出其 tps，即抽样个数越大，其统计越精确。</p>
<blockquote>
<p>温馨提示：上面的方法在学习了上文的滑动窗口设计原理后将显得非常简单，大家在学习的过程中，可以总结出一个规律，什么时候时候使用秒级滑动窗口，什么时候使用分钟级滑动窗口。</p>
</blockquote>
<h4 id="2-5-metrics"><a href="#2-5-metrics" class="headerlink" title="2.5 metrics"></a>2.5 metrics</h4><p>由于 Sentienl 基于滑动窗口来实时收集统计信息，并存储在内存中，并随着时间的推移，旧的滑动窗口将失效，故需要提供一个方法，及时将所有的统计信息进行汇总输出，供监控客户端定时拉取，转储都其他客户端，例如数据库，方便监控数据的可视化，这也通常是中间件用于监控指标的监控与采集的通用设计方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Map&lt;Long, MetricNode&gt; <span class="title">metrics</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">long</span> currentTime = TimeUtil.currentTimeMillis();</span><br><span class="line">    currentTime = currentTime - currentTime % <span class="number">1000</span>;   <span class="comment">// @1</span></span><br><span class="line">    Map&lt;Long, MetricNode&gt; metrics = <span class="keyword">new</span> ConcurrentHashMap&lt;&gt;();</span><br><span class="line">    List&lt;MetricNode&gt; nodesOfEverySecond = rollingCounterInMinute.details();   <span class="comment">// @2</span></span><br><span class="line">    <span class="keyword">long</span> newLastFetchTime = lastFetchTime;</span><br><span class="line">    <span class="comment">// Iterate metrics of all resources, filter valid metrics (not-empty and up-to-date).</span></span><br><span class="line">    <span class="keyword">for</span> (MetricNode node : nodesOfEverySecond) &#123; </span><br><span class="line">        <span class="keyword">if</span> (isNodeInTime(node, currentTime) &amp;&amp; isValidMetricNode(node)) &#123;    <span class="comment">// @3</span></span><br><span class="line">	    metrics.put(node.getTimestamp(), node);</span><br><span class="line">            newLastFetchTime = Math.max(newLastFetchTime, node.getTimestamp());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    lastFetchTime = newLastFetchTime;</span><br><span class="line">    <span class="keyword">return</span> metrics;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：获取当前时间对应的滑动窗口的开始时间，可以对比上文计算滑动窗口的算法。</p>
<p>代码@2：获取一分钟内的所有滑动窗口中的统计数据，使用 MetricNode 表示。</p>
<p>代码@3：遍历所有节点，刷选出不是当前滑动窗口外的所有数据。这里的重点是方法：isNodeInTime。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">isNodeInTime</span><span class="params">(MetricNode node, <span class="keyword">long</span> currentTime)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> node.getTimestamp() &gt; lastFetchTime &amp;&amp; node.getTimestamp() &lt; currentTime;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里只刷选出不是当前窗口的数据，即 metrics 方法返回的是“过去”的统计数据。</p>
<p>接下来我们再来看看 DefaultNode 相关的几个特性方法。</p>
<h2 id="3、DefaultNode-详解"><a href="#3、DefaultNode-详解" class="headerlink" title="3、DefaultNode  详解"></a>3、DefaultNode  详解</h2><h4 id="3-1-类图"><a href="#3-1-类图" class="headerlink" title="3.1 类图"></a>3.1 类图</h4><p><img src="https://img-blog.csdnimg.cn/20200119211434219.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>DefaultNode 是 StatisticNode 的子类，其额外增加的属性如下：</p>
<ul>
<li>private ResourceWrapper id<br>资源id，即 DefaultNode 才真正与资源挂钩，可以将 DefaultNode 看出是调用链中的一个节点，并且与资源关联。</li>
<li>private volatile Set&lt; Node &gt; childList<br>子节点结合。以此来维持其调用链。</li>
<li>private ClusterNode clusterNode<br>集群节点，同样为 StatisticNode 的子类，表示与资源集群相关的环境。</li>
</ul>
<p>接下来我们将来看一下 DefaultNode 的核心方法。</p>
<h4 id="3-2-increaseBlockQps"><a href="#3-2-increaseBlockQps" class="headerlink" title="3.2 increaseBlockQps"></a>3.2 increaseBlockQps</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">increaseBlockQps</span><span class="params">(<span class="keyword">int</span> count)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>.increaseBlockQps(count);</span><br><span class="line">    <span class="keyword">this</span>.clusterNode.increaseBlockQps(count);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>DefaultNode 的此类方法，通常是先调用 StatisticNode 的方法，然后再调用 clusterNode 的相关方法，最终就是使用在对应的滑动窗口中增加或减少计量值。</p>
<p>其他方法也比较简单，就不再细看了，我们可以通过 DefaultNode 的 printDefaultNode 方法来打印该节点的调用链。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/e7bbdda0.html" rel="next" title="Sentinel 调用上下文环境实现原理">
                <i class="fa fa-chevron-left"></i> Sentinel 调用上下文环境实现原理
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/a815ae71.html" rel="prev" title="Sentinel 集群限流设计原理">
                Sentinel 集群限流设计原理 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90-StatisticSlot"><span class="nav-number">1.</span> <span class="nav-text">1、源码分析 StatisticSlot</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-StatisticSlot-entry-%E8%AF%A6%E8%A7%A3"><span class="nav-number">1.0.1.</span> <span class="nav-text">1.1 StatisticSlot entry 详解</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-StatisticSlot-exit-%E8%AF%A6%E8%A7%A3"><span class="nav-number">1.0.2.</span> <span class="nav-text">1.2 StatisticSlot exit 详解</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81Sentienl-Node-%E4%BD%93%E7%B3%BB"><span class="nav-number">2.</span> <span class="nav-text">2、Sentienl Node 体系</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81StatisticNode-%E8%AF%A6%E8%A7%A3"><span class="nav-number">3.</span> <span class="nav-text">2、StatisticNode 详解</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-%E6%A0%B8%E5%BF%83%E7%B1%BB%E5%9B%BE"><span class="nav-number">3.0.1.</span> <span class="nav-text">2.1 核心类图</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-addPassRequest"><span class="nav-number">3.0.2.</span> <span class="nav-text">2.2 addPassRequest</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-totalRequest"><span class="nav-number">3.0.3.</span> <span class="nav-text">2.3 totalRequest</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4-successQps"><span class="nav-number">3.0.4.</span> <span class="nav-text">2.4 successQps</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-5-metrics"><span class="nav-number">3.0.5.</span> <span class="nav-text">2.5 metrics</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3%E3%80%81DefaultNode-%E8%AF%A6%E8%A7%A3"><span class="nav-number">4.</span> <span class="nav-text">3、DefaultNode  详解</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-%E7%B1%BB%E5%9B%BE"><span class="nav-number">4.0.1.</span> <span class="nav-text">3.1 类图</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2-increaseBlockQps"><span class="nav-number">4.0.2.</span> <span class="nav-text">3.2 increaseBlockQps</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
